package top.lshaci.learning.springboot.rabbitmq.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.lshaci.learning.springboot.rabbitmq.model.SpringBootMessage;
import top.lshaci.learning.springboot.rabbitmq.model.SpringMessage;

import java.io.IOException;

/**
 * SpringBootHandler
 *
 * <pre>
 *     必须 @EnableRabbit 才能使用 @RabbitListener
 *
 *     使用 RabbitTemplate.convertAndSend(exchange, routingKey, message); 发送自定义对象消息
 *     会在消息头中添加 headers: __TypeId__: top.lshaci.learning.spring.boot.rabbitmq.model.SpringBootMessage, 自定义对象全限定名
 *     使用 @RabbitHandler 接收消息的时候，会通过消息头中的 __TypeId__ 将消息转换为指定对象
 * </pre>
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
@Component
@RabbitListener(queues = "springboot")
public class SpringBootHandler {

    @RabbitHandler(isDefault = true)
    public void springboot(Message rawMessage, SpringBootMessage message, Channel channel) throws IOException {
        log.debug("接收到消息：{}", message);
        log.debug("rawMessage：{}", rawMessage);
        log.debug("channel：{}", channel);
        log.debug("correlationId：{}", rawMessage.getMessageProperties().getCorrelationId());
        // channel内按照顺序自增
        long deliveryTag = rawMessage.getMessageProperties().getDeliveryTag();
        // 手动进行ack
        channel.basicAck(deliveryTag, false);
    }

    @RabbitHandler
    public void springboot(Message rawMessage, SpringMessage message, Channel channel) {
        log.debug("接收到消息：{}", message);
        log.debug("rawMessage：{}", rawMessage);
        log.debug("channel：{}", channel);
    }
}
